#include <Stepper.h>

const int trigPin = 9; // Trigger pin for HC-SR04
const int echoPin = 10; // Echo pin for HC-SR04

const int motorPin1 = 2; // IN1 for 28BYJ stepper motor
const int motorPin2 = 3; // IN2 for 28BYJ stepper motor
const int motorPin3 = 4; // IN3 for 28BYJ stepper motor
const int motorPin4 = 5; // IN4 for 28BYJ stepper motor

Stepper stepper(512, motorPin1, motorPin3, motorPin2, motorPin4); // 28BYJ has 512 steps per revolution

unsigned long previousMillis = 0; // 用于存储上一次执行操作的时间
const long interval = 5000; // 定时间隔为10秒

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  stepper.setSpeed(10); // Set the motor speed (adjust as needed)
}

void loop() {
  unsigned long currentMillis = millis(); // 获取当前时间

  long duration, distance;


  // Trigger the HC-SR04 to measure distance
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the echo time to calculate distance
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  Serial.print("Distance: ");
  Serial.println(distance);
  

  // 如果检测到障碍物距离小于10厘米，则投放食物
  if (distance < 10) {
    dispenseFood();
    delay(1000); // Wait for stability, adjust as needed
  }

  // 检查是否到达定时间间隔，执行食物投放操作
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis; // 更新上一次执行操作的时间
    dispenseFood(); // 执行食物投放操作
  }
}

void dispenseFood() {
  // Rotate the stepper motor by 2 steps
  stepper.step(200);
  delay(1000); // Adjust delay based on your specific mechanism and requirements
  // Stop the stepper motor
  stepper.step(0);
}